//
//  CustomeEvaluate.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/12/12.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "CustomeEvaluate.h"
#import "CustomeEvaluateSectionView.h"
#import "ServiceEvaluationCell.h"
#import "ShopEvaluationModel.h"
#import "ShopEvaluationAssociationModel.h"
#import "ShopEvaluationEvaluateInfosModel.h"
#import "YHPhotoBrowser.h"
#import "ServiceModel.h"
#import "ArrowheadMenu.h"
@interface CustomeEvaluate ()<ServiceEvaluationCellDelegate,CustomeEvaluateSectionViewDelegate,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate,MenuViewControllerDelegate>
@property(nonatomic,strong) CustomeEvaluateSectionView *sectionView;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,assign) NSInteger page;
@property(nonatomic,assign) NSInteger row;
@property(nonatomic,assign) NSInteger type;
@property(nonatomic,assign) NSInteger uid;
@property(nonatomic,strong) NSMutableArray *shopEvaluationMuta;
@property(nonatomic,strong) NSMutableArray *shopEvaluationAssociationMuta;
@property(nonatomic,strong) NSMutableArray *shopEvaluationEvaluateInfosMuta;
@property(nonatomic,strong) AFHTTPSessionManager  *manager;
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,strong) ShopEvaluationEvaluateInfosModel *complainModel;
@end
static NSString *identifier = @"cell";
@implementation CustomeEvaluate
-(NSMutableArray *)shopEvaluationMuta
{
    if (!_shopEvaluationMuta) {
        _shopEvaluationMuta = [NSMutableArray array];
    }
    return _shopEvaluationMuta;
}
-(NSMutableArray *)shopEvaluationAssociationMuta
{
    if (!_shopEvaluationAssociationMuta) {
        _shopEvaluationAssociationMuta = [NSMutableArray array];
    }
    return _shopEvaluationAssociationMuta;
}
-(NSMutableArray *)shopEvaluationEvaluateInfosMuta
{
    if (!_shopEvaluationEvaluateInfosMuta) {
        _shopEvaluationEvaluateInfosMuta = [NSMutableArray array];
    }
    return _shopEvaluationEvaluateInfosMuta;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.complainModel = [[ShopEvaluationEvaluateInfosModel alloc]init];
    self.manager = [AFHTTPSessionManager manager];
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [self.tableView registerNib:[UINib nibWithNibName:@"ServiceEvaluationCell" bundle:nil] forCellReuseIdentifier:identifier];
    self.page = 1;
    self.row = 10;
    self.type = 0;
    [self reloadInternetData];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadMore)];
    self.tableView.mj_footer = footer;
                [footer setTitle:[NSBundle bundleLocalizedStringForKey:@"footerTitle"]
 forState:MJRefreshStateNoMoreData];
                footer.stateLabel.font = [UIFont systemFontOfSize:12];
                footer.stateLabel.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1];
    
}
-(void)reloadMore
{
    self.page ++;
    [self reloadInternetData];
}
- (void)setModel:(ServiceModel *)model
{
    _model = model;
//    self.shopEvaluationEvaluateInfosMuta = nil;
     
}
-(void)reloadInternetData
{
    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    [WSProgressHUD show];
    NSInteger empty = [EmptyModel stringIsNullOrEmpty:self.model];
    if (empty !=1) {
        self.urlString = [NSString stringWithFormat:@"%@/associationEvaluate/list",kUrl];
        self.dict = @{
                      @"aid":[NumberSwitchString numberSwitchString:self.model.id],
                      @"page":[NumberSwitchString numberSwitchString:self.page],
                      @"rows":[NumberSwitchString numberSwitchString:self.row],
                      @"type":[NumberSwitchString numberSwitchString:self.type],
                      @"uid":[UserDefaultsHelper readUid]
                      };
    }else {
        self.urlString = [NSString stringWithFormat:@"%@/associationEvaluate/listByMUid",kUrl];
        self.dict = @{
                      @"page":[NumberSwitchString numberSwitchString:self.page],
                      @"rows":[NumberSwitchString numberSwitchString:self.row],
                      @"type":[NumberSwitchString numberSwitchString:self.type],
                      @"uid":[UserDefaultsHelper readUid]
                      };
        XLog(@"self.dict:%@",self.dict);
        
    }
    [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        XLog(@"responseObject:%@",responseObject);
        NSDictionary *date = [responseObject objectForKey:@"date"];
        ShopEvaluationModel *shopEvaluationModel = [ShopEvaluationModel mj_objectWithKeyValues:date];
        [self.shopEvaluationMuta addObject:shopEvaluationModel];
        NSArray *evaluateInfos =  [date objectForKey:@"evaluateInfos"];
        XLog(@"evaluateInfos.count:%ld",evaluateInfos.count);
        if (evaluateInfos.count) {
            for (NSDictionary *dict in evaluateInfos) {
                XLog(@"dict:%@",dict);
                ShopEvaluationEvaluateInfosModel *shopEvaluationEvaluateInfosModel = [ShopEvaluationEvaluateInfosModel mj_objectWithKeyValues:dict];
                [self.shopEvaluationEvaluateInfosMuta addObject:shopEvaluationEvaluateInfosModel];
                NSDictionary *association = [dict objectForKey:@"association"];
                ShopEvaluationAssociationModel *shopEvaluationModel = [ShopEvaluationAssociationModel mj_objectWithKeyValues:association];
                [self.shopEvaluationAssociationMuta addObject:shopEvaluationModel];
            }
            if (evaluateInfos.count< 10) {
                self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
            }else {
                [self.tableView.mj_footer endRefreshing];
            }
        }else {
            self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        }
        if (!self.shopEvaluationEvaluateInfosMuta.count) {
            self.tableView.emptyDataSetSource = self;
            self.tableView.emptyDataSetDelegate = self;
            [self.tableView.mj_footer removeFromSuperview];
        }
        [self.tableView reloadData];
        [WSProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    XLog(@"self.shopEvaluationEvaluateInfosMuta.count:%ld",self.shopEvaluationEvaluateInfosMuta.count);
    return self.shopEvaluationEvaluateInfosMuta.count?self.shopEvaluationEvaluateInfosMuta.count:0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    ServiceEvaluationCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ShopEvaluationEvaluateInfosModel *shopEvaluationEvaluateInfosModel = self.shopEvaluationEvaluateInfosMuta[indexPath.row];
    cell.shopEvaluationEvaluateInfosModel = shopEvaluationEvaluateInfosModel;
    ShopEvaluationAssociationModel *shopEvaluationModel = self.shopEvaluationAssociationMuta[indexPath.row];
    cell.shopEvaluationModel = shopEvaluationModel;
    cell.delegate = self;
    cell.indexPath = indexPath;
    return cell;
}
#pragma mark-代理:查看评论图片
-(void)serviceEvaluationCell:(ServiceEvaluationCell *)serviceEvaluationCell withLookImage:(NSArray *)images
{
    XLog(@"images:%@",images);
    YHPhotoBrowser *photoView=[[YHPhotoBrowser alloc]init];
    photoView.urlImgArr=images;           //网络链接图片的数组
    photoView.indexTag=0;                      //初始化进去显示的图片下标
    [photoView show];

}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    self.sectionView = [[CustomeEvaluateSectionView alloc]initWithFrame:CGRectMake(0, kVWidth, 0, 60)];
    self.sectionView.delegate = self;
    if (self.shopEvaluationMuta.count) {
        self.sectionView.model = self.shopEvaluationMuta[0];
    }
    return self.sectionView;
    
}
#pragma mark-代理:全部,好评,中评,差评
- (void)customeEvaluateSectionView:(CustomeEvaluateSectionView *)customeEvaluateSectionView withBtn:(UIButton *)btn
{
    self.type = btn.tag-1;
    self.page = 1;
    self.shopEvaluationAssociationMuta = nil;
    self.shopEvaluationMuta = nil;
    self.shopEvaluationEvaluateInfosMuta = nil;
    [self reloadInternetData];
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 60;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 0,1)];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
#pragma mark-代理:更新点赞
- (void)serviceEvaluationCell:(ServiceEvaluationCell *)serviceEvaluationCell withGiveLikeBtn:(UIButton *)giveLikeBtn withIndexPath:(NSIndexPath *)indexPath withShopEvaluationEvaluateInfosModel:(ShopEvaluationEvaluateInfosModel *)shopEvaluationEvaluateInfosModel
{
    XLog(@"indexPath.row:%ld",indexPath.row);
    giveLikeBtn.selected = !giveLikeBtn.selected;
    NSString *ids = [NSString stringWithFormat:@"%ld",shopEvaluationEvaluateInfosModel.id];
    NSDictionary *dict = @{
                           @"uid":[UserDefaultsHelper readUid],
                           @"id":ids
                           };
    XLog(@"dict:%@",dict);
    self.urlString = [NSString stringWithFormat:@"%@/associationEvaluate/updateSupportCount",kUrl];
    [self.manager POST:self.urlString parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        XLog(@"responseObject:%@",responseObject);
        NSString *message = [responseObject objectForKey:@"message"];
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    ShopEvaluationEvaluateInfosModel *mode = self.shopEvaluationEvaluateInfosMuta[indexPath.row];
    if (giveLikeBtn.selected) {
        mode.supportcount++;
    }else {
        mode.supportcount--;
    }
    mode.isSupport = giveLikeBtn.selected;
    //    [self.tableView reloadData];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    
}
#pragma mark-代理:评价投诉
- (void)serviceEvaluationCell:(ServiceEvaluationCell *)serviceEvaluationCell withShopEvaluationEvaluateInfosModel:(ShopEvaluationEvaluateInfosModel *)shopEvaluationEvaluateInfosModel withComplaintBtn:(UIButton *)complaintBtn
{
    self.urlString = [NSString stringWithFormat:@"%@/associationevaluatecomplains/select",kUrl];
    self.dict = @{
                  @"uid":[UserDefaultsHelper readUid],
                  @"token":[UserDefaultsHelper readToken],
                  @"aeid":[NumberSwitchString numberSwitchString:shopEvaluationEvaluateInfosModel.id]
                  };
    XLog(@"self.dict:%@",self.dict);
    [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        XLog(@"responseObject:%@",responseObject);
        NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
        NSString *date = [responseObject objectForKey:@"date"];
        NSString *message = @"";
        if ([date integerValue] == 0) {
            message = @"投诉";
        }else {
            message = @"已投诉";
        }
        self.complainModel = shopEvaluationEvaluateInfosModel;
        ArrowheadMenu *vc = [[ArrowheadMenu alloc] initDefaultArrowheadMenuWithTitle:@[message] icon:@[@"tousu"] menuPlacements:ShowAtBottom ];
        vc.delegate = self;
        [vc presentMenuView:complaintBtn];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}
// 菜单代理方法
- (void)menu:(BaseMenuViewController *)menu didClickedItemUnitWithTag:(NSInteger)tag andItemUnitTitle:(NSString *)title {
    if (tag == 0) {
        [menu removeMenuView];
        UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]||[UserDefaultsHelper readAutoLogIn].length == 0) {
            LogInOrOutVC *logVC = [[LogInOrOutVC alloc]init];
            MainNavC *mainNav = [[MainNavC alloc]initWithRootViewController:logVC];
            [viewController presentViewController:mainNav animated:YES completion:nil];
            XLog(@"投");
        }else {
            __weak typeof (self)weakSelf = self;
            self.dict = @{
                          @"userId":[UserDefaultsHelper readUid],
                          @"token":[UserDefaultsHelper readToken]
                          };
            self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
            [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
                if (status == 200) {
                    if ([title isEqualToString:@"投诉"]) {
                        self.urlString = [NSString stringWithFormat:@"%@/associationevaluatecomplains/save",kUrl];
                        self.dict = @{
                                      @"uid":[UserDefaultsHelper readUid],
                                      @"token":[UserDefaultsHelper readToken],
                                      @"aeid":[NumberSwitchString numberSwitchString:self.complainModel.id]
                                      };
                        XLog(@"self.dict:%@",self.dict);
                        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                            XLog(@"responseObject:%@",responseObject);
                            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
                            if (status == 200) {
                                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"投诉成功"];
                            }
                        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                            
                        }];
                    }else {
                        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"不可重复投诉"];
                    }
                }else {
                    [UIAlertViewWarningAccount showWarningAccount];
                    [LogOutAccount presentOutAccount];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
            
        }
    }
    
    
    
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    UIImage *image = [UIImage imageNamed:@"empty"];
    return image;
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = [NSBundle bundleLocalizedStringForKey:@"noData"];
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:14],
                                 NSForegroundColorAttributeName:kLabel102Color
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}
@end
